<template>
  <el-row class="search-form" :class="{ 'order-list': hasBgColor }">
    <el-form ref="form" :inline="true" :label-width="`${labelWidth}px`">
      <el-col v-for="(item, index) of items" :key="index" :span="6">
        <el-form-item :label="item.name">
          <el-input
            v-if="!item.type || item.type === 'input'"
            v-model="searchParams[item.key]"
            size="small"
            v-bind="setAttrs(item)"
            :placeholder="item.placeholder || '请输入'"
          />
          <el-select
            v-else-if="item.type === 'select'"
            v-model="searchParams[item.key]"
            v-bind="setAttrs(item)"
            allow-clear
            size="small"
            :placeholder="item.placeholder || '请选择'"
          >
            <el-option
              v-for="(option, i) of item.options"
              :key="i"
              :value="
                option[(item['props'] && item['props']['value']) || 'value']
              "
              :label="
                option[(item['props'] && item['props']['key']) || 'label']
              "
            />
          </el-select>
          <el-autocomplete
            v-else-if="item.type === 'remote'"
            v-model="searchParams[item.key]"
            clearable
            size="small"
            :fetch-suggestions="
              (queryString, cb) => {
                remoteMethod(queryString, cb, item);
              }
            "
            :placeholder="item.placeholder || '请输入'"
          />
          <!-- <el-select
            v-else-if="item.type === 'remote'"
            v-model="searchParams[item.key]"
            size="small"
            multiple
            filterable
            remote
            reserve-keyword
            v-bind="setAttrs(item)"
            :placeholder="item.placeholder || '请输入'"
            :remote-method="query => {remoteMethod(query, item)}"
            :loading="remoteLoading"
          >
            <el-option
              v-for="v in remoteOptions"
              :key="v.value"
              :label="v.label"
              :value="v.value"
            />
          </el-select> -->
          <el-cascader
            v-else-if="item.type === 'cascader'"
            v-model="searchParams[item.key]"
            :placeholder="item.placeholder || '请选择'"
            v-bind="setAttrs(item)"
            size="small"
            :options="item.options"
          />
          <el-date-picker
            v-else-if="item.type === 'date-picker'"
            v-model="searchParams[item.key]"
            prefix-icon=""
            :placeholder="item.placeholder || '请选择'"
            v-bind="setAttrs(item)"
            size="small"
            :type="item.pickerType || 'daterange'"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <template v-else-if="item.type === 'section'">
            <el-input
              v-model="searchParams[item.minKey]"
              class="section-input"
              v-bind="setAttrs(item)"
              size="small"
              :placeholder="item.placeholder || '请输入'"
            /><span class="symbol">-</span><el-input
              v-model="searchParams[item.maxKey]"
              class="section-input"
              size="small"
              v-bind="setAttrs(item)"
              :placeholder="item.placeholder || '请输入'"
            />
          </template>
        </el-form-item>
      </el-col>
      <div class="button-group">
        <el-form-item class="button" label=" ">
          <!-- button 前置插槽 -->
          <slot name="prefix-button" />
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <!-- button 后置插槽 -->
          <slot name="suffix-button" />
        </el-form-item>
      </div>
    </el-form>
    <div class="extra-button-container">
      <slot name="extra-button" />
      <div class="extra-button-right">
        <slot name="extra-button-right" />
      </div>
    </div>
  </el-row>
</template>
<script>
/**
 * dom结构基于element-ui 依赖于 element-ui 的 row form input select cascader date-picker button等组件
 * cloneDeep方法依赖于lodash库
 * items 为过滤条件，可以在对应的项中自定义下拉选项的名称（optionNamekey）和值（optionValuekey）的键，默认分别取 name 和 id
 * items 如何要下拉框显示 placeholder，对应的下拉框的初始值可以设置为 undefined 或者 不定义查询参数，如果设置为空， placeholder 不会显示。
 * searchParams 为接口查询参数对象
 *
 * items 示例：
 * [{ name: '发起人1', value: 123, key: 'name1', placeholder: 'xxxxx' },{name: '输入框',value: '选项1',key: 'repairerId',type: 'select',options: [{value: '选项1', label: '黄金糕'},{value: '选项2',label: '双皮奶'}]},{ name: '时间', key: 'roomId', type: 'date-picker', options: [] }]
 */
import request from '@/utils/request'
export default {
  name: 'TableFilter',
  props: {
    order: {
      type: Boolean,
      default: false
    },
    hasBgColor: {
      type: Boolean,
      default: false
    },
    // 表单参数
    searchParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 表单配置
    items: {
      type: Array,
      default: () => {
        return []
      }
    },
    labelWidth: {
      type: Number,
      default: 120
    }
  },
  data() {
    return {
      // 保存初始化时的项
      initSearchParams: {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // 保存初始值的
      console.log(this.searchParams, 'searchParams')
      // eslint-disable-next-line no-undef
      this.initSearchParams = _.cloneDeep(this.searchParams)
    },
    handleSearch() {
      console.log(this.searchParams, 'searchParams')
      // eslint-disable-next-line no-undef
      const cpValue = _.cloneDeep(this.searchParams)
      this.$emit('update:searchParams', { ...cpValue, request: true })
      this.$emit('change', cpValue)
      this.$emit('search', cpValue)
    },
    handleReset() {
      // eslint-disable-next-line no-undef
      const cpValue = _.cloneDeep(this.initSearchParams)
      console.log(cpValue, 'cpValuecpValue')
      !this.order
        ? this.$emit('update:searchParams', { ...cpValue, request: true })
        : ''
      this.$emit('change', cpValue)
      this.$emit('reset', cpValue)
    },
    // 联想搜索
    async remoteMethod(queryString, cb, params) {
      const { resultKey, keyName } = params
      let response = await this.requestApi(params, queryString)
      const result = []
      response =
        Object.prototype.toString.call(response) === '[object Array]'
          ? response
          : response[keyName]
      response.map(item => {
        result.push({ value: item[resultKey] })
      })
      cb(result)
    },
    // 请求接口封装成动态接收api地址
    async requestApi(params, query = '') {
      const { url, searchKey, requestParams } = params
      const reqOpt = url.split('|')
      const [method, _url] = reqOpt[1] ? reqOpt : ['post', reqOpt[0]]
      const reqKey = reqOpt[2]
        ? reqOpt[2]
        : method.toLowerCase() === 'post'
          ? 'data'
          : 'params'
      requestParams[searchKey] = query
      try {
        const res = await request({
          url: _url,
          method,
          [reqKey]: requestParams,
          config: {
            hideError: true
          }
        })
        return res
      } catch (e) {
        return []
      }
    },
    // 绑定属性 继承element相关组件的全部属性
    setAttrs(params) {
      // eslint-disable-next-line
      const { slot, ...options } = params;
      return { ...options }
    }
  }
}
</script>
<style lang="scss" scoped>
.order-list {
  background-color: #f5f7fa;
  height: 131px;
  padding: 20px 20px 0 0;
}
.search-form {
  margin: 0;
  .el-form {
    overflow: hidden;
  }
  ::v-deep .el-form-item {
    display: flex;
    width: 100%;
    .el-form-item__label {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
    }
    .el-form-item__content {
      flex: 1;
    }
  }
  // .el-col {
  // margin-right: 60px;
  //  ::v-deep .el-form-item__label{width: auto !important;}
  // &:first-of-type{
  //  ::v-deep .el-form-item__label{width: auto !important;}
  // }
  // }
  ::v-deep .el-input,
  .el-cascader,
  .el-select,
  .el-autocomplete,
  .el-date-editor {
    width: 100%;
  }
  ::v-deep.section-input {
    width: calc((100% - 20px) / 2);
  }
  .symbol {
    display: inline-block;
    text-align: center;
    width: 20px;
  }
  .button-group {
    display: inline-block;
    vertical-align: top;
  }
  .extra-button-container {
    .extra-button-right {
      float: right;
    }
  }
}
</style>
